package com.kischang.blog.service;

import com.kischang.blog.dao.UserDao;
import com.kischang.blog.model.User;
import com.kischang.blog.utils.Utils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;

@Component
public class UserService {
	@Resource
	private UserDao userDao;
	
	@Transactional(readOnly=true)
	public boolean checkUsernameIsExists(String username){
		return userDao.findUserByUsername(username)!=null;
	}
	
	@Transactional(readOnly=true)
	public User findUserByUsername(String username){
		return userDao.findUserByUsername(username);
	}
	
	@Transactional
	public void updateLastLoginTime(User user){
		String time = Utils.formatDate(Calendar.getInstance().getTime());
		userDao.updateLastLogin(user.getId(),time);
		user.setLastLogin(time);
	}

	@Transactional
	public void updateTicket(User user, String pwcookie) {
		userDao.updateTicket(user,pwcookie);
	}
	

	@Transactional
	public void updateTicketAndLastlogin(User user, String pwcookie) {
		userDao.updateTicketAndLastlogin(user,pwcookie,Utils.formatDate());
	}

	@Transactional(readOnly=true)
	public boolean checkTicket(User user, String pwcookie) {
		String ticket = userDao.getUserTicket(user);
		return pwcookie.equals(ticket);
	}

	@Transactional
	public void saveUser(User user) {
		userDao.save(user);
	}

    @Transactional(readOnly=true)
    public List<User> getAll() {
        return userDao.getAll();
    }
}
